package cn.yousuowei.huanglele.scanmine;

import android.content.Context;
import android.content.Intent;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class MineActivity extends AppCompatActivity implements AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener{

    // girdview 布局
    private GridView mine_grid;

    // girdview 适配器里面的数据
    private List<Map<String,Object>> mine_data;
    // girdview 适配器
    private ListAdapter adapter;
    // 当前难度级别 intent 传参
    private int level = 0;
    // 当前难度的具体信息
    Map<String,Object> current_param;
    private int current_row;
    private int current_col;

    // 难度配置
    private List<Map<String,Object>> level_param;

    // 上下文
    private Context mContext;

    // 雷的布局
    private Mine mine_position;


    private TextView mine_level_name;   // 级别
    private TextView mine_all_num;      // 总雷数
    private Button mine_return_btn;     // 返回按钮
    private TextView mine_used_time;    //用时
    private TextView mine_found_num;    // 找到的雷数量
    private Button mine_restart_btn;    // 重新开始

    private int found_mine_num = 0;
    private int all_mine_num = 0;   // 所有的雷数量
    private int start_time = 0;
    private int found_safety_box = 0;    // 已经找到的安全区块的数量
    private int game_status = 0;        // 游戏状态0暂停，1进行中
    private int all_box_num = 0;       // 格子总数量

    private Timer timer = new Timer();
    private TimerTask task = new TimerTask() {
        @Override
        public void run() {
            if(game_status == 1){
                start_time++;
                String s = getPrettyUsedTime();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshUsedTime();
                    }
                });
            }
        }
    };

    private String getPrettyUsedTime(){
        int t = this.start_time;
        int h = 0;
        int m = 0;
        int s = 0;
        String text = "";
        if(t >= 3600){
            h = (int) Math.floor(t / 3600);
            t = t % 3600;
        }
        if(t >= 60){
            m = (int) Math.floor(t / 60);
            t = t % 60;
        }
        if(h > 0){
            text = h+"小时 ";
        }
        if(m > 0){
            text += m + "分 ";
        }
        s = t;
        text += s + "秒";
        return  text;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mine);
        this.mContext = this;

        // 获取intent的参数
        Intent intent = getIntent();
        this.level = intent.getIntExtra("level",0);
        initLevelParam();
        initGame();
        timer.schedule(task,1000,1000);
    }

    protected void refreshUsedTime(){
        mine_used_time.setText(getPrettyUsedTime());
    }

    /**
     * 设置参数
     */
    private void initLevelParam(){
        int[] levels = {0,1,2};
        int[] cols = {9,16,16};
        int[] rows = {9,16,30};
        int[] mines = {10,40,100};
        String[] dif = {"初级","中级","高级"};
        level_param = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < 3; i++){
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("level",levels[i]);
            map.put("col",cols[i]);
            map.put("row",rows[i]);
            map.put("mine",mines[i]);
            map.put("dif",dif[i]);
            level_param.add(map);
        }
    }

    /**
     * 设置适配器的数据
     * @return
     */
    private List<Map<String,Object>> getMineData(){
        mine_data = new ArrayList<Map<String, Object>>();
        mine_grid.setNumColumns((int)current_param.get("col"));
        int l = (int)current_param.get("col") * (int)current_param.get("row");
        for (int i = 0; i < l; i++){
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("bg",R.drawable.off);
            map.put("text","");
            map.put("is_open",0);       // 是否点开
            map.put("status",mine_position.getPlaceNum(i)); // 雷的信息
            map.put("result",0);       // 结果 0：没有点开 ，1：设置为雷，2：疑问
            mine_data.add(map);
        }
        return mine_data;
    }


    /**
     * 初始化游戏
     */
    private void initGame(){
        mine_grid = (GridView) findViewById(R.id.mine_grid);
        start_time = 0;
        game_status = 1;

        // 设置当前级别信息
        current_param = this.level_param.get(level);
        // 设置 格子二位数组
        current_col = (int) current_param.get("col");
        current_row = (int) current_param.get("row");
        all_box_num = current_row * current_col;
        int num = (int) current_param.get("mine");
        mine_position = new Mine(current_row,current_col,num);
        adapter = new SimpleAdapter(this,getMineData(),R.layout.grid_mine,new String[]{"bg","text"},new int[]{R.id.mine_box_btn,R.id.mine_num});
        mine_grid.setAdapter(adapter);
        // 设置点击监听事件
        mine_grid.setOnItemClickListener(this);
        // 设置长按事件
        mine_grid.setOnItemLongClickListener(this);


        // 设置游戏提示信息
        mine_level_name = (TextView) findViewById(R.id.mine_level_name);
        mine_level_name.setText((String)current_param.get("dif"));

        mine_all_num = (TextView) findViewById(R.id.mine_all_num);
        all_mine_num = (int) current_param.get("mine");
        mine_all_num.setText(all_mine_num + "");

        mine_return_btn = (Button) findViewById(R.id.mine_return_btn);
        // 点击返回上一个界面
        mine_return_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,MainActivity.class);
                startActivity(intent);
                finish();
            }
        });

        mine_restart_btn = (Button) findViewById(R.id.mine_restart_btn);
        // 点击重新开始
        mine_restart_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initGame();
            }
        });

        mine_used_time = (TextView) findViewById(R.id.mine_used_time);
        mine_found_num = (TextView) findViewById(R.id.mine_found_num);
        found_mine_num = 0;
        refeshFoundMineNum();
    }

    private void refeshFoundMineNum(){
        mine_found_num.setText("" + found_mine_num);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ImageView img = (ImageView) view.findViewById(R.id.mine_box_btn);
        TextView textView = (TextView) view.findViewById(R.id.mine_num);
        Map<String,Object> mine = mine_data.get(position);

        // 判断当前位置是否是雷
        int mine_status = (int) mine.get("status");
        if(mine_status == 9){
            // 雷
            gameOver(position);
        }else {
            // 非雷 显示提示
            showBoxRes(position);
            if(mine_status == 0){
                autoShowSafetyBox(position);
            }
//            if(mine_status == 0){
//                textView.setText("");
//                // 这是一个空白区域 自动显示他的四周
//                autoShowSafetyBox(position);
//            }else {
//                textView.setText(mine_status + "");
//            }
//            img.setImageResource(R.drawable.on);
        }
    }


    private void gameOver(int p){
        game_status = 0;
        showBoxRes(p);
        jumpResult(false);
    }

    private void jumpResult(boolean is_win){
        Intent intent = new Intent(mContext,ResultActivity.class);
        intent.putExtra("used_time","用时"+getPrettyUsedTime());
        intent.putExtra("is_win",is_win);
        intent.putExtra("level",level);
        startActivity(intent);
//        finish();
    }

    private void showBoxRes(int p){
        p = p - mine_grid.getFirstVisiblePosition();
        View box = mine_grid.getChildAt(p);
        ImageView img = (ImageView) box.findViewById(R.id.mine_box_btn);
        TextView textView = (TextView) box.findViewById(R.id.mine_num);
        Map<String,Object> mine = mine_data.get(p);
        int mine_status = (int) mine.get("status");
        int is_open = (int) mine.get("is_open");
        mine.put("is_open",1);
        if(mine_status == 0 || mine_status == 9){
            textView.setText("");
        }else {
            textView.setText(mine_status + "");
        }
        if(mine_status == 9){
            img.setImageResource(R.drawable.bom);
        }else {
            img.setImageResource(R.drawable.on);

        }
        if(is_open == 0){
            found_safety_box++;
            Log.i("found_safety_box",found_safety_box+"--"+p);
            if((found_safety_box + found_mine_num) == all_box_num){
                // 挑战成功
                game_status = 0;
                jumpResult(true);
            }
        }
    }

    /**
     * 自动展示周围的空白处
     * @param p
     */
    private void autoShowSafetyBox(int p){
        Coord coord = new Coord(current_row,current_col,p);
        int i = coord.getCurrent_row();
        int j = coord.getCurrent_col();
        for (int ii = i-1; ii <= i+1; ii++ ){
            for (int jj = j-1; jj <= j+1; jj++){
                if(ii >= 0  && ii < this.current_row && jj >= 0 && jj < this.current_col){
                    int p_temp = coord.RcToPosition(ii,jj);
                    Log.i("found_safety_box_xy","["+i+","+j+"]----["+ii+","+jj+"]");
                    // 获取当前的数据
                    Map<String,Object> mine = mine_data.get(p_temp);
                    if( (int) mine.get("is_open") == 1){
                        // 已经打开了
                        continue;
                    }
                    showBoxRes(p_temp);
                    // 判断是否又是一个绝对安全的空格
                    if((int) mine.get("status") == 0){
                        autoShowSafetyBox(p_temp);
                    }
                }
            }
        }
    }

    // 长按事件
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if(this.game_status == 1){
            ImageView img = (ImageView) view.findViewById(R.id.mine_box_btn);
            Map<String,Object> mine = mine_data.get(position);
            int result = (int) mine.get("result");
            int open = (int) mine.get("is_open");
            if(open == 1){
                // 已经打开了
                showBoxRes(position);
            }else {
                switch (result){
                    case 0:
                        if(found_mine_num < all_mine_num){
                            img.setImageResource(R.drawable.flag);
                            found_mine_num++;
                            refeshFoundMineNum();
                        }
                        break;
                    case 1: // 当前是标记为雷
                        img.setImageResource(R.drawable.question);
                        found_mine_num--;
                        refeshFoundMineNum();
                        break;
                    case 2: // 当前是问号
                        img.setImageResource(R.drawable.off);break;
                }
                result = ++result % 3;
                mine.put("result",result);
            }
        }
        return true;    //不执行点击事件
    }


    /**
     * 点击返回退出到桌面
     */
    @Override
    public void onBackPressed() {
        Intent home = new Intent(Intent.ACTION_MAIN);
        home.addCategory(Intent.CATEGORY_HOME);
        startActivity(home);
    }

}
